const fs = require('fs');
const path = require('path');
const { 
  buildLogPath, 
  ensureDirectoryExists,
  getRootPath 
} = require('../utils/path');
const { getLocalISOString } = require('../utils/date');
const { validLevels, levelPriority, matchLogLevel } = require('../utils/levels');

const isDevelopment = process.env.NODE_ENV === 'development';
const isDebug = process.env.LOG_DEBUG === 'true';

/**
 * 日志类
 */
class Logger {
  /**
   * 创建日志实例
   * @param {Object} options 配置选项
   * @param {string} options.logDir 日志目录
   */
  constructor(options = {}) {
    this.logDir = options.logDir || path.join(getRootPath(), 'logs');
  }

  /**
   * 记录日志
   * @param {string} level 日志级别
   * @param  {...any} messages 日志消息
   */
  log(level, ...messages) {
    // 确保是有效的日志级别
    if (!validLevels.includes(level)) {
      level = matchLogLevel(level);
    }

    const currentLevelPriority = levelPriority[level];
    const envLevel = process.env.LOG_LEVEL?.toLowerCase();
    const envLevelPriority = levelPriority[envLevel] ??
      (isDevelopment ? levelPriority['debug'] : levelPriority['info']);

    // 如果当前级别低于环境设置的级别，则不记录
    if (currentLevelPriority < envLevelPriority) {
      return;
    }

    const now = new Date();
    const logFilePath = buildLogPath(this.logDir, level, now);
    ensureDirectoryExists(path.dirname(logFilePath));

    const formattedMessages = messages.map(msg => {
      if (typeof msg === 'string') return msg;
      if (msg === null || msg === undefined) return String(msg);
      try {
        return JSON.stringify(msg, null, 2);
      } catch (err) {
        
        if (isDevelopment || isDebug) {
          console.error('JSON序列化错误:', err);
        }
        return msg.toString();
      }
    });

    const logContent = `${getLocalISOString(now)} - ${formattedMessages.join(' ')}\n`;
    try {
      fs.appendFileSync(logFilePath, logContent);
    } catch (err) {
      
      if (isDevelopment || isDebug) {
        console.error(`写入日志文件失败: ${err}`);
      }
    }
  }

  /**
   * 记录 trace 级别日志
   * @param  {...any} messages 日志消息
   */
  trace(...messages) {
    this.log('trace', ...messages);
  }

  /**
   * 记录 debug 级别日志
   * @param  {...any} messages 日志消息
   */
  debug(...messages) {
    this.log('debug', ...messages);
  }

  /**
   * 记录 info 级别日志
   * @param  {...any} messages 日志消息
   */
  info(...messages) {
    this.log('info', ...messages);
  }

  /**
   * 记录 warn 级别日志
   * @param  {...any} messages 日志消息
   */
  warn(...messages) {
    this.log('warn', ...messages);
  }

  /**
   * 记录 error 级别日志
   * @param  {...any} messages 日志消息
   */
  error(...messages) {
    this.log('error', ...messages);
  }

  /**
   * 记录 fatal 级别日志
   * @param  {...any} messages 日志消息
   */
  fatal(...messages) {
    this.log('fatal', ...messages);
  }
}

module.exports = Logger;